import React, { useState } from 'react'
import { View, Input, Image } from '@tarojs/components'
import Taro from '@tarojs/taro'
import PageWrapper from '@/components/PageWrapper'
import { request } from '@/utils/request'

import './index.scss';

const Page = () => {
  const [name, setName] = useState('')
  const [idCard, setIdCard] = useState('')

  const handleSubmit = async () => {
    if (!name || !idCard) {
      Taro.showToast({ title: '请填写完整信息', icon: 'none' })
      return
    }

    try {
      await request.post('/member/user/real-name-auth', { name, idCard }, true)
      Taro.showToast({ title: '实名认证成功', icon: 'success' })

      // 可选：更新缓存 userInfo
      const userInfo = Taro.getStorageSync('userInfo') || {}
      Taro.setStorageSync('userInfo', { ...userInfo, name, idCard, realNameAuth: true })

      // 可选：返回上一页或刷新当前页
      const pages = Taro.getCurrentPages()
      const prevPage = pages[pages.length - 2]
      if (prevPage) {
        prevPage.onLoad(prevPage.options)
        Taro.navigateBack()
      }
    } catch (err) {
      console.error(err)
      Taro.showToast({ title: '实名认证失败', icon: 'none' })
    }
  }

  return (
    <PageWrapper title="实名认证" showBack={true} backgroundColor='#FE7407' color="#ffffff">
      <View className="my-service-page">
        <View className="my-service">
          <Image src={require(`../../../assets/user/real-name-bg.png`)} />
        </View>
        <View className="title-item-box">
          <View className="title-item">填写信息</View>
          <View className="online-goods-item">
            <View className="online-goods-title">真实姓名：</View>
            <Input
              className="online-goods-input"
              placeholder="请输入"
              value={name}
              onInput={e => setName(e.detail.value)}
            />
          </View>
          <View className="online-goods-item">
            <View className="online-goods-title">身份证号：</View>
            <Input
              className="online-goods-input"
              placeholder="请输入"
              value={idCard}
              onInput={e => setIdCard(e.detail.value)}
            />
          </View>
        </View>
        <View className="submit-but" onClick={handleSubmit}>实名认证</View>
      </View>
    </PageWrapper>
  )
}

export default Page
